package org.geektimes.projects.user.sql;

import org.geektimes.comtext.ClassicComponentContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ComponentDBConnectionManager {

    private final Logger logger = Logger.getLogger(ComponentDBConnectionManager.class.getName());

    public Connection getConnection(){
        final ClassicComponentContext context = ClassicComponentContext.getInstance();
        //依赖查找
        DataSource dataSource = context.getComponent("jdbc/UserPlatformDB");
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
        if (connection != null) {
            logger.log(Level.INFO, "获取 JNDI 数据库连接成功！");
            System.out.println("获取 JNDI 数据库连接成功！");
        }
        return connection;
    }

}
